#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/6 12:35
# @Author : 闫峰
# @File    : discount.py
import time

import requests

from third_services.shopee.base_tool import shop_auth, db, shop_auth_shop
from utils.otherutils.json_format import json_format
from third_services.shopee.common.common_func import get_timestamp, get_access_token, get_shop_id


class InterfaceDiscount:
    base_url = "https://partner.shopeemobile.com"
    timestamp = int(time.time())
    partner_id = 2001656

    def add_discount_item(self, ordersourceid,
                          apiService="/api/v2/discount/add_discount_item"):
        """使用此api获取一个商店折扣活动的详细信息"""
        sign = shop_auth_shop(ordersourceid, apiService)
        sql1 = """	SELECT CertIdAccessKeyId,UserTokenSecretAccessKey  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.execute_sql(sql1, (ordersourceid,))
        access_token = res1["UserTokenSecretAccessKey"]
        shop_id = res1["CertIdAccessKeyId"]
        url = self.base_url + apiService
        payload = {
            "discount_id": 721948913048214,
            "item_list": [
                {
                    "item_id": 14198879374,
                    "purchase_limit": 5,
                    "item_promotion_price": 382
                    # "model_list": [
                    #     {
                    #         "model_id": 137574899419,
                    #         "model_promotion_price": 382
                    #     },
                    #     {
                    #         "model_id": 137574899420,
                    #         "model_promotion_price": 324
                    #     },
                    #     {
                    #         "model_id": 137574899421,
                    #         "model_promotion_price": 372
                    #     },
                    #     {
                    #         "model_id": 137574899418,
                    #         "model_promotion_price": 319
                    #     }
                    # ]
                }
            ]
        }
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": sign,
            "shop_id": shop_id

        }
        response = requests.request("POST", url, headers=headers, json=payload, params=param, allow_redirects=False)

        return response.json()

    def delete_discount_item(self, ordersourceid,
                             apiService="/api/v2/discount/delete_discount_item"):
        """使用此api获取一个商店折扣活动的详细信息"""
        sign = shop_auth_shop(ordersourceid, apiService)
        sql1 = """	SELECT CertIdAccessKeyId,UserTokenSecretAccessKey  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.execute_sql(sql1, (ordersourceid,))
        access_token = res1["UserTokenSecretAccessKey"]
        shop_id = res1["CertIdAccessKeyId"]
        url = self.base_url + apiService
        payload = {
            "discount_id": 718443999527450,
            "item_id": 23341800047}
        headers = {}
        timestamp = int(time.time())
        param = {
            "partner_id": self.partner_id,
            "timestamp": timestamp,
            "access_token": access_token,
            "sign": sign,
            "shop_id": shop_id

        }
        response = requests.request("POST", url, headers=headers, json=payload, params=param, allow_redirects=False)

        return response.json()

    def api_v2_product_add_discount_item(self, ordersourceid,
                                         apiService="/api/v2/discount/add_discount_item"):
        """使用此api获取一个商店折扣活动的详细信息
        discount_status:  upcoming/ongoing/expired/all
        """
        sign = shop_auth_shop(ordersourceid, apiService)
        sql1 = """	SELECT CertIdAccessKeyId,UserTokenSecretAccessKey  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.execute_sql(sql1, (ordersourceid,))
        access_token = res1["UserTokenSecretAccessKey"]
        shop_id = res1["CertIdAccessKeyId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "shop_id": shop_id

        }
        data = {
            "discount_id": 713788800240025,
            "item_list": [
                {
                    "item_id": 14997055558,
                    "purchase_limit": 5,
                    "item_promotion_price": 8.84
                }
            ]
        }
        data1 = {
            "discount_id": 713788800240025,
            "item_list": [
                {
                    "item_id": 22235622311,
                    "purchase_limit": 5,
                    "model_list": [
                        {
                            "model_id": 49288262600,
                            "model_promotion_price": 9.97
                        }
                    ]
                }
            ]
        }
        response = requests.request("POST", url, headers=headers, data=payload, params=param, json=data1,
                                    allow_redirects=False)

        return json_format(response.json())

    def delete_discount(self, ordersourceid, discount_id, apiService="/api/v2/discount/delete_discount"):
        """
        使用此api获取一个商店折扣活动的详细信息
        discount_status:  upcoming/ongoing/expired/all
        """
        sign = shop_auth_shop(ordersourceid, apiService)
        sql1 = """	SELECT CertIdAccessKeyId,UserTokenSecretAccessKey  FROM sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s;"""
        res1 = db.execute_sql(sql1, (ordersourceid,))
        access_token = res1["UserTokenSecretAccessKey"]
        shop_id = res1["CertIdAccessKeyId"]
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": self.timestamp,
            "access_token": access_token,
            "sign": sign,
            "shop_id": shop_id

        }
        data = {
            "discount_id": discount_id
        }
        response = requests.request("POST", url, headers=headers, data=payload, params=param, json=data,
                                    allow_redirects=False)

        return json_format(response.json())

    def get_discount_list(self, ordersourceid, page_no, apiService="/api/v2/discount/get_discount_list"):
        """
        使用此api获取一个商店折扣活动的详细信息
        discount_status:  upcoming/ongoing/expired/all
        """
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "discount_status": "ongoing",
            "page_no": page_no,
            "page_size": 100
        }

        response = requests.request("POST", url, headers=headers, data=payload, params=param, json=payload,
                                    allow_redirects=False).json()

        # return json_format(response.json())
        count = 0
        while True:

            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "discount_status": "ongoing",
                    "page_no": page_no,
                    "page_size": 100
                }
                count += 1
                print(count)
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break
        return response

    def get_discount(self, ordersourceid, discount_id, page_no, apiService="/api/v2/discount/get_discount"):
        url = self.base_url + apiService
        payload = {}
        headers = {}
        param = {
            "partner_id": self.partner_id,
            "timestamp": get_timestamp(),
            "access_token": get_access_token(ordersourceid),
            "sign": shop_auth_shop(ordersourceid, apiService),
            "shop_id": get_shop_id(ordersourceid),
            "discount_id": discount_id,
            "page_no": page_no,
            "page_size": 50

        }
        response = requests.request("POST", url, headers=headers, data=payload, params=param,
                                    allow_redirects=False).json()
        while True:
            if response['error'] == 'error_sign':
                param = {
                    "partner_id": self.partner_id,
                    "timestamp": get_timestamp(),
                    "access_token": get_access_token(ordersourceid),
                    "sign": shop_auth_shop(ordersourceid, apiService),
                    "shop_id": get_shop_id(ordersourceid),
                    "discount_id": discount_id,
                    "page_no": page_no,
                    "page_size": 50

                }
                response = requests.request("GET", url, headers=headers, data=payload, params=param,
                                            allow_redirects=False).json()
            else:
                break

        return response


if __name__ == '__main__':
    # 根据渠道id 活动id 获得所有参加活动的产品列表
    # res = InterfaceDiscount().get_discount(14092,718443999527450, 1)
    # print(InterfaceDiscount().delete_discount(14052, 676836612908162))
    # 根据渠道id 活动状态 获取所有的活动id
    # print(InterfaceDiscount().api_v2_product_get_discount_list(14260,"ongoing", 1, 100))
    # print(InterfaceDiscount().get_discount_list(14260,"ongoing",1))
    # print(InterfaceDiscount().get_discount_list(14257,1))
    res = InterfaceDiscount().add_discount_item(14267)
    print(json_format(res))
    # print(InterfaceDiscount().delete_discount_item(14092))
